<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共 {{ page.total }} 条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push({ path: '/import' })"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportEmployees"
          >导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="List">
          <el-table-column label="序号" sortable="">
            <template slot-scope="scope">
              {{
                page.page > 1
                  ? (page.page - 1) * page.size + (scope.$index + 1)
                  : scope.$index + 1
              }}
            </template>
          </el-table-column>
          <el-table-column label="头像" sortable="" width="200">
            <template slot-scope="{ row }">
              <img
                v-imgerr="require('@/assets/common/head.jpg')"
                class="avatar"
                :src="row.staffPhoto"
                alt=""
                @click="showQRCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            sortable=""
            :formatter="formatFormEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template slot-scope="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push('employees/detail/' + row.id)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignrole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            :current-page="page.page"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <addemployess :show-dialog="showDialog" />

      <el-dialog title="头像预览" :visible="isShowQRCode" @close="isShowQRCode=false">
        <el-row type="flex" justify="center">
          <canvas ref="mycanvas" />
        </el-row>
      </el-dialog>

      <AssignRole ref="assignrole" :user-id="userId" :show-role-dialog.sync="showRoleDialog" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import { formatDate } from '@/filters'
import addemployess from './components/addemployess'
import QRCode from 'qrcode'
// 对于一个不常用的库, 每次都默认引入, 技术上没问题
// 可以进行优化
// import {export_json_to_excel} from '@/vendor/Export2Excel'
import AssignRole from './components/assign-role'
export default {
  components: {
    addemployess,
    AssignRole
  },
  data() {
    return {
      //
      userId: '',
      showRoleDialog: false,
      showDialog: false,
      isShowQRCode: false,
      List: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      }
    }
  },
  created() {
    // 渲染页面
    this.getEmployeeList()
  },
  methods: {
    // checkPermission(pointName) {
    //   // 这里是判断当前用户是否有权限的函数
    //   // 如果这个权限点名称存在于用户数据的points 权限数组中就可以点击
    //   // 否则则不能
    //   return this.$store.getters.roles && this.$store.getters.roles.points.includes(pointName)
    // },
    // 点击弹出角色管理
    async assignrole(id) {
      // 等到请求到数据后在弹窗
      await this.$refs.assignrole.getUserDetailById(id)
      this.userId = id
      this.showRoleDialog = true
    },
    // 点击生成二维码
    showQRCode(url) {
      // url = url || require('@/assets/common/head.jpg')
      if (url) {
        this.isShowQRCode = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.mycanvas, url, {
            width: 300,
            color: {
              dark: '#5081fd'
            }
          })
        })
      }
    },
    // 点击导出excel表格
    async exportEmployees() {
      // 这里是按钮被点击, 可以就在这里单独引入需要的库
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.page.total
      })
      // console.log(rows)
      // console.log(export_json_to_excel)
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '地址'],
      //   data: [
      //     ['小明', 888, '珠吉路58号'],
      //     ['小红', 8, '珠吉路59号'],
      //     ['小刚', 12, '珠吉路60号']
      //   ]
      // })
      const dict = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      // console.log(Object.keys(dict))

      const userData = rows.map((user) => {
        return this.object2Arrayy(user, dict)
      })

      // console.log(userData)

      export_json_to_excel({
        header: Object.keys(dict),
        data: userData
      })
    },
    // 改变数据格式
    object2Arrayy(user, dict) {
      const newUser = []
      for (const key in dict) {
        const enkey = dict[key]
        const value = user[enkey]
        // 如果是时间的数据不能直接放,而是应该进行转换
        if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          // 格式化日期
          newUser.push(new Date(formatDate(value)))
        } else if (enkey === 'formOfEmployment') {
          newUser.push(value === 1 ? '正式工' : '临时工')
        } else {
          newUser.push(value)
        }
      }
      return newUser
    },
    // 渲染页面的方法
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.page)
      // console.log(rows, total)
      this.page.total = total
      this.List = rows
    },
    // 跳转页面
    changePage(newpage) {
      this.page.page = newpage
      this.getEmployeeList()
    },
    formatFormEmployment(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      return cellValue === 1 ? '正式工' : '临时工'
    },
    // 点击删除
    async delEmployee(id) {
      // 二次校验
      await this.$confirm('是否确认删除')
      // 发请求
      await delEmployee(id)
      // 提示用户
      this.$message.success('删除成功')
      // 刷新页面
      this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 200px;
  height: 200px;
  object-fit: contain;
}
</style>
